const path = require('path')
const fs = require('fs-extra')
const inquirer = require('inquirer')
const spawn = require('cross-spawn')
const ora = require('ora')
const figlet = require('figlet')
const chalk = require('chalk')
const Listr = require('listr')
const { getPackageManager } = require('./utils')
const templateList = [
  {
    name: 'ts-library-scaffolding',
    value: 'ts-library-scaffolding',
    gitee: 'https://gitee.com/Talent-HYJ/ts-library-scaffolding.git',
    github: '',
  },
  {
    name: 'Electron-React',
    value: 'electron-react',
    gitee: 'https://gitee.com/Talent-HYJ/electron-react-template.git',
    github: 'https://github.com/Talent-HYJ/electron-react-template.git',
  },
]
async function selectTemplate() {
  const { template } = await inquirer.prompt([
    {
      name: 'template',
      type: 'list',
      message: '请选择模板：',
      choices: templateList,
    },
  ])
  return templateList.find(item => item.value === template)
}

async function selectDownloadAddress() {
  const { downloadAddress } = await inquirer.prompt([
    {
      name: 'downloadAddress',
      type: 'list',
      message: '请选择下载地址：',
      choices: [
        {
          name: 'gitee',
          value: 'gitee',
        },
        {
          name: 'github',
          value: 'github',
        },
      ],
    },
  ])
  return downloadAddress
}
async function gitCloneProject(name) {
  const template = await selectTemplate()
  if (!template.gitee && !template.github) {
    console.log(chalk.yellow('暂不支持该模板下载'))
    process.exit(0)
  }
  const cwd = process.cwd()
  const targetDir = path.join(cwd, name)
  const address = await selectDownloadAddress()
  const tasks = new Listr([
    {
      title: 'download package',
      task: () => {
        const spinner = ora('正在下载模板...').start()
        const res = spawn.sync('git', ['clone', template[address], name])
        spinner.stop()
        return res
      },
    },
    {
      title: 'install package dependencies',
      task: async (ctx, task) => {
        const packageManager = await getPackageManager()
        const spinner = ora('正在安装依赖...').start()
        if (packageManager === 'yarn') {
          const res = spawn.sync('yarn', [], {
            cwd: targetDir,
            shell: true,
          })
          spinner.stop()
          return res
        } else {
          const res = spawn.sync('npm', ['install'], {
            cwd: targetDir,
            shell: true,
          })
          spinner.stop()
          return res
        }
      },
    },
  ])
  tasks
    .run()
    .then(() => {
      figlet('SUCCESS!', (err, data) => {
        if (err) {
          console.log('Something went wrong...')
          return
        }
        console.log(data)
      })
    })
    .catch(error => {
      console.log(chalk.red(error))
    })
}

module.exports = async function create(name, options) {
  // 当前命令行执行的目录
  const cwd = process.cwd()
  // 创建的项目的路径
  const targetDir = path.join(cwd, name)
  if (fs.existsSync(targetDir)) {
    // 是否覆盖
    if (options.force) {
      await fs.remove(targetDir)
    } else {
      let { action } = await inquirer.prompt([
        {
          name: 'action',
          type: 'list',
          message: '目录已存在，是否覆盖？',
          choices: [
            {
              name: '覆盖',
              value: 'overwrite',
            },
            {
              name: '取消',
              value: 'cancel',
            },
          ],
        },
      ])
      if (!action) {
        return
      } else if (action === 'overwrite') {
        // 删除目录
        await fs.remove(targetDir)
        gitCloneProject(name)
      }
    }
  } else {
    // https://gitee.com/Talent-HYJ/electron-react-template.git
    try {
      gitCloneProject(name)
    } catch (error) {
      console.log(error)
    }
  }
}
